package cn.ekuma.epos.analysis.productStockDiary;


import cn.ekuma.epos.core.util.ProductSwingUtil;
import cn.ekuma.epos.datalogic.I_DataLogicERP;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.epos.module.ERP_UI_Swing_Model;
import cn.ekuma.rabbit.spi.I_ModelPart;

import com.openbravo.beans.JCalendarDialog;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.ComboBoxValModel;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.query.QBFCompareEnum;
import com.openbravo.data.user.EditorCreator;
import com.openbravo.format.Formats;

import com.openbravo.pos.base.*;
import com.openbravo.bean.Location;
import com.openbravo.bean.Product;
import com.openbravo.pos.forms.JPanelView;
import com.openbravo.pos.panels.JProductDetailMini;
import com.openbravo.pos.panels.JProductFinder;
import com.openbravo.pos.panels.QuickTimerFilter;
import com.openbravo.pos.panels.event.TimeCycleChangedEvent;
import com.openbravo.pos.panels.event.TimeCycleChangedListener;
import java.util.Date;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import org.jdesktop.swingx.JXTable;
import javax.swing.JTextField;

public class JProductStockDiaryAnalysisPanel extends javax.swing.JPanel implements JPanelView, BeanFactoryApp,EditorCreator, TimeCycleChangedListener,I_ModelPart<ERP_UI_Swing_Model>{
    private I_DataLogicERP  dlSales;
    private I_DataLogicSystem dlSystem;
    private AnalysisModelManager manager;
	private QuickTimerFilter timerFilter;
	Object[] beforeFilterParas;
	private JProductFinder productFinder;
	private JProductDetailMini productDetail;
	
	private JComboBox m_jLocation;
	private  JXTable table;
    
    /** Creates new form JProductAnalysisPanel */
    public JProductStockDiaryAnalysisPanel() {
    	initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setLayout(new java.awt.BorderLayout());
    	
    	panel = new JPanel();
    	panel.setPreferredSize(new Dimension(10, 200));
    	add(panel, BorderLayout.NORTH);
    	panel.setLayout(new BorderLayout(0, 0));
    	
    	        jToolBar1 = new javax.swing.JToolBar();
    	        panel.add(jToolBar1, BorderLayout.NORTH);
    	        
    	        timerFilter=new QuickTimerFilter();
    	        panel.add(timerFilter,BorderLayout.SOUTH);
    	        timerFilter.addTimeCycleChangedListener(this);
    	        jtxtCustomer = new javax.swing.JTextField();
    	        jtxtCustomer.addActionListener(new ActionListener() {
    	        	public void actionPerformed(ActionEvent e) {
    	        		incProductByCode(jtxtCustomer.getText());
    	        	}
    	        });
    	        btnCustomer = new javax.swing.JButton();
    	        jLabel3 = new javax.swing.JLabel();
    	        jTxtStartDate = new javax.swing.JTextField();
    	        btnDateStart = new javax.swing.JButton();
    	        jLabel4 = new javax.swing.JLabel();
    	        jTxtEndDate = new javax.swing.JTextField();
    	        btnDateEnd = new javax.swing.JButton();
    	        productDetail=new JProductDetailMini();
    	        panel.add(productDetail, BorderLayout.CENTER);
    	        
    	                jToolBar1.setRollover(true);
    	                        
    	                                jtxtCustomer.setPreferredSize(new java.awt.Dimension(100, 25));
    	                                jToolBar1.add(jtxtCustomer);
    	                                
    	                                        btnCustomer.setIcon(new ImageIcon(JProductStockDiaryAnalysisPanel.class.getResource("/com/openbravo/images/search.png"))); // NOI18N
    	                                        btnCustomer.setFocusPainted(false);
    	                                        btnCustomer.setFocusable(false);
    	                                        btnCustomer.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    	                                        btnCustomer.setMargin(null);
    	                                        btnCustomer.setPreferredSize(new java.awt.Dimension(55, 25));
    	                                        btnCustomer.setRequestFocusEnabled(false);
    	                                        btnCustomer.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    	                                        btnCustomer.addActionListener(new java.awt.event.ActionListener() {
    	                                            public void actionPerformed(java.awt.event.ActionEvent evt) {
    	                                                btnCustomerActionPerformed(evt);
    	                                            }
    	                                        });
    	                                        jToolBar1.add(btnCustomer);
    	                                                
    	                                                lotNO = new JTextField();
    	                                                lotNO.addActionListener(new ActionListener() {
    	                                                	public void actionPerformed(ActionEvent e) {
    	                                                		reQuery();
    	                                                	}
    	                                                });
    	                                                jToolBar1.add(lotNO);
    	                                                lotNO.setColumns(10);
    	                                        
    	                                                jLabel3.setText(AppLocal.getIntString("Label.StartDate")); // NOI18N
    	                                                jToolBar1.add(jLabel3);
    	                                                
    	                                                        jTxtStartDate.setMinimumSize(new java.awt.Dimension(6, 15));
    	                                                        jTxtStartDate.setPreferredSize(new java.awt.Dimension(150, 22));
    	                                                        jToolBar1.add(jTxtStartDate);
    	                                                        
    	                                                                btnDateStart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/date.png"))); // NOI18N
    	                                                                btnDateStart.setFocusable(false);
    	                                                                btnDateStart.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    	                                                                btnDateStart.setPreferredSize(new java.awt.Dimension(55, 25));
    	                                                                btnDateStart.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    	                                                                btnDateStart.addActionListener(new java.awt.event.ActionListener() {
    	                                                                    public void actionPerformed(java.awt.event.ActionEvent evt) {
    	                                                                        btnDateStartActionPerformed(evt);
    	                                                                    }
    	                                                                });
    	                                                                jToolBar1.add(btnDateStart);
    	                                                                
    	                                                                        jLabel4.setText(AppLocal.getIntString("Label.EndDate")); // NOI18N
    	                                                                        jToolBar1.add(jLabel4);
    	                                                                        
    	                                                                                jTxtEndDate.setPreferredSize(new java.awt.Dimension(150, 22));
    	                                                                                jToolBar1.add(jTxtEndDate);
    	                                                                                
    	                                                                                        btnDateEnd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/date.png"))); // NOI18N
    	                                                                                        btnDateEnd.setFocusable(false);
    	                                                                                        btnDateEnd.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    	                                                                                        btnDateEnd.setPreferredSize(new java.awt.Dimension(55, 25));
    	                                                                                        btnDateEnd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    	                                                                                        btnDateEnd.addActionListener(new java.awt.event.ActionListener() {
    	                                                                                            public void actionPerformed(java.awt.event.ActionEvent evt) {
    	                                                                                                btnDateEndActionPerformed(evt);
    	                                                                                            }
    	                                                                                        });
    	                                                                                        jToolBar1.add(btnDateEnd);
    	                                                                                                                
    	                                                                                        m_jLocation = new JComboBox();
    	                                                                                		m_jLocation.setPreferredSize(new Dimension(150, 21));
    	                                                                                		jToolBar1.add(m_jLocation);
    	                                                                                                                btnNewButton_1 = new JButton("");
    	                                                                                                                btnNewButton_1.addActionListener(new ActionListener() {
    	                                                                                                                	public void actionPerformed(ActionEvent e) {
    	                                                                                                                		m_jResert1ActionPerformed(e);
    	                                                                                                                	}
    	                                                                                                                });
    	                                                                                                                btnNewButton_1.setIcon(new ImageIcon(JProductStockDiaryAnalysisPanel.class.getResource("/com/openbravo/images/reload.png")));
    	                                                                                                                jToolBar1.add(btnNewButton_1);
    	                                                                                                                JScrollPane scrollPane = new JScrollPane();
    	                                                                            	        	         	        table = new JXTable();
    	                                                                            	        	         	       scrollPane.setViewportView(table);
    	
    	add(scrollPane, BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    
    private void incProductByCode(String sCode) {
        if(sCode.isEmpty()){
           return ;
        }
        boolean isSeachModel=false;
        // precondicion: sCode != null
        sCode.toUpperCase();
        try {
            Product oProduct=null;
            if(sCode.startsWith("~")){
            	isSeachModel=true;
                  java.util.List<Product> prods=dlSales.listProductByMnemonic(sCode.substring(1));
                  if(prods!=null&&prods.size()>0)
                      if(prods.size()==1)
                         oProduct=prods.get(0);
                      else
                         oProduct=getProductFinder().setProductList(prods);
            }else{
                oProduct = ProductSwingUtil.getProductInfo(this, dlSales, sCode.trim());
            }
            if (oProduct == null) {                  
                Toolkit.getDefaultToolkit().beep(); 
                	new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.noproduct")).show(this);
            } else { 
            	productDetail.detailProduct(oProduct);
            	reQuery();
            }
        } catch (BasicException eData) {
            new MessageInf(eData).show(this);           
        }
    }

	public JProductFinder getProductFinder() {
        if(productFinder==null)
            productFinder=JProductFinder.getInstance(this, dlSales,JProductFinder.PRODUCT_ALL);
        return productFinder;
    }

	private void btnCustomerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCustomerActionPerformed
		Product obj=getProductFinder().showMessage(this, dlSales);
		if(obj!=null)
			productDetail.detailProduct(obj);
		reQuery();
			
}//GEN-LAST:event_btnCustomerActionPerformed

    private void btnDateStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDateStartActionPerformed
        Date date;
        try {
            date = (Date) Formats.TIMESTAMP.parseValue(jTxtStartDate.getText());
        } catch (BasicException e) {
            date = null;
        }
        date = JCalendarDialog.showCalendarTimeHours(this, date);
        if (date != null) {
            jTxtStartDate.setText(Formats.TIMESTAMP.formatValue(date));
        }
}//GEN-LAST:event_btnDateStartActionPerformed

    private void btnDateEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDateEndActionPerformed
        Date date;
        try {
            date = (Date) Formats.TIMESTAMP.parseValue(jTxtEndDate.getText());
        } catch (BasicException e) {
            date = null;
        }
        date = JCalendarDialog.showCalendarTimeHours(this, date);
        if (date != null) {
            jTxtEndDate.setText(Formats.TIMESTAMP.formatValue(date));
        }
}//GEN-LAST:event_btnDateEndActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCustomer;
    private javax.swing.JButton btnDateEnd;
    private javax.swing.JButton btnDateStart;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField jTxtEndDate;
    private javax.swing.JTextField jTxtStartDate;
    private javax.swing.JTextField jtxtCustomer;
    private JPanel panel;
	private JButton btnNewButton_1;
	protected String productId;
	private ComboBoxValModel m_LocationsModel;
	private JTextField lotNO;

    public String getTitle() {
        return "";
    }

    public void activate() throws BasicException {
    	List locationList=null;
        try {
            locationList=dlSales.list(Location.class);
        } catch (BasicException ex) {
            new MessageInf(ex).show(this);
        }
        m_LocationsModel = new ComboBoxValModel(locationList);
        m_jLocation.setModel(m_LocationsModel); // para que lo refresque
        if(locationList.size()>0)
            m_jLocation.setSelectedIndex(0);
        
    }

    public boolean deactivate() {
        return true;
    }

    public JComponent getComponent() {
        return this;
    }

    public void init(I_AppView app) throws BeanFactoryException {
        manager= new AnalysisModelManager(dlSales);
    }
    
    private void reQuery(){
    	if(productDetail.getObj()==null)
    		return;
        try{
        if(beforeFilterParas==null)
        	beforeFilterParas=(Object[]) createValue();
        beforeFilterParas[6] = QBFCompareEnum.COMP_EQUALS;
        beforeFilterParas[7] = productDetail.getObj().getID();
        String lot=lotNO.getText();
        if(lot==null||lot.isEmpty()){
        	beforeFilterParas[8]=QBFCompareEnum.COMP_NONE;
            beforeFilterParas[9]=null;
        }else{
        	beforeFilterParas[8]=QBFCompareEnum.COMP_RE;
            beforeFilterParas[9]=lot;
        }
        
     	manager.query(beforeFilterParas);
     	table.setModel(manager.getDialeyTableModel());
      } catch (BasicException ex) {
         new MessageInf(ex).show(this);
     }
     }
    
    
    public Object getBean() {
        return this;
    }

	protected void m_jResert1ActionPerformed(ActionEvent e) {
		beforeFilterParas=null;
		jTxtStartDate.setText(null);
		jTxtEndDate.setText(null);
		jtxtCustomer.setText(null);
		timerFilter.resert();
		lotNO.setText(null);
		productDetail.detailProduct(null);
	}
    
    
    public Object createValue() throws BasicException {
    	Object[] afilter=new Object[10];
        
        // Date range
       Object startdate = Formats.TIMESTAMP.parseValue(jTxtStartDate.getText());
       Object enddate = Formats.TIMESTAMP.parseValue(jTxtEndDate.getText());

       afilter[0] = (startdate == null) ? QBFCompareEnum.COMP_NONE : QBFCompareEnum.COMP_GREATEROREQUALS;
       afilter[1] = startdate;
       afilter[2] = (enddate == null) ? QBFCompareEnum.COMP_NONE : QBFCompareEnum.COMP_LESS;
       afilter[3] = enddate;

       if(m_jLocation.getSelectedItem()==null){
           afilter[4] = QBFCompareEnum.COMP_NONE;
           afilter[5] = null;
       }else{
           afilter[4] = QBFCompareEnum.COMP_EQUALS;
           afilter[5] = ((Location)m_jLocation.getSelectedItem()).getID();
       } 

      // Product
        afilter[6]=QBFCompareEnum.COMP_NONE;
        afilter[7]=null;
        
        // LotNO
        afilter[8]=QBFCompareEnum.COMP_NONE;
        afilter[9]=null;
 

       return afilter;
    }

	@Override
	public void timeCycleChanged(TimeCycleChangedEvent e) {
		if(beforeFilterParas==null)
			try {
				beforeFilterParas=(Object[]) createValue();
			} catch (BasicException ex) {
				new MessageInf(ex).show(this);
				return;
			}
			Object startdate =e.getStartDate();
	        Object enddate = e.getEndDate();
	        
			beforeFilterParas[0] = (startdate == null) ? QBFCompareEnum.COMP_NONE : QBFCompareEnum.COMP_GREATEROREQUALS;
			beforeFilterParas[1] = startdate;
			beforeFilterParas[2] = (enddate == null) ? QBFCompareEnum.COMP_NONE : QBFCompareEnum.COMP_LESS;
			beforeFilterParas[3] = enddate;	
			reQuery();
			jTxtStartDate.setText(Formats.TIMESTAMP.formatValue(startdate));
		    jTxtEndDate.setText(Formats.TIMESTAMP.formatValue(enddate));
	}

	@Override
	public String getModelName() {
		return ERP_UI_Swing_Model.MODEL_NAME;
	}

	@Override
	public void setModel(ERP_UI_Swing_Model mode) {
		 dlSales=mode.getDLERP();
	     dlSystem=mode.getDLSystem();
	}
}